HSQL on Tomcat

Ever wanted to know how to make an instance of HSQL start up and stop with Tomcat? Look no further…

It gives you a free way to have a database server and app server integrated together.

I had a requirement for this a while back and I figured that I’d better share the code:

package com.company.cso.hsql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.hsqldb.Server;

public class HSQLDBUtility {

private static String PORT = "8675";

public static void start() {
final String database = "c:\\path-to-save\\database-files";
final String port = PORT;
if (database != null) {
Thread server = new Thread() {
public void run() {
System.out.println("Starting HSQLDB");
String[] args = {
"-database", database,
"-port", port,
"-no_system_exit", "true" };
Server.main(args);
}
};
server.start();
}
}

public static void stop() {
try {
System.out.println("Stopping HSQLDB");
final Connection con = DriverManager.getConnection("jdbc:hsqldb://localhost:"+ PORT);
con.createStatement().execute("SHUTDOWN");
} catch (SQLException e) {
System.out.println("ERROR shutting down HSQLDB");
}
}
}

 

package com.company.cso.hsql;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;

public class TomcatHSQLDBPlugin implements LifecycleListener {
   public void lifecycleEvent(LifecycleEvent event) {
      if (event.getType().equals(Lifecycle.START_EVENT)) {
         HSQLDBUtility.start();
      }
      else if (event.getType().equals(Lifecycle.STOP_EVENT)) {
         HSQLDBUtility.stop();
      }
      else {
         System.out.println(getClass().getName()+": Not handling LifecycleEvent: "+event.getType());
      }
   }
}

 


The first class takes care of the setup of the db server. The second class implements the LifecycleListener interface that plugs into the tomcat server.xml.

~ by dkuntze on January 28, 2009.

Leave a comment